import router from '@/router'
import { getToken, getTimeStamp } from '@/utils/auth'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'

//设置白名单
const whiteList = ['/404', '/login']

router.beforeEach(async (to, from, next) => {
  // 访问的路径在白名单
  const token = getToken()
  NProgress.start()
  if (token) {
    const time = 30 * 60 * 1000
    // console.log(2);
    //判断用户是否存在
    // const time = 5000
    const currentTime = Date.now()
    const spaceTime = currentTime - getTimeStamp()
    if (spaceTime >= time) {
      store.dispatch('user/logout')
      console.log(window.location.href.split('#')[1])
      router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
      return
    }
    const userInfo = store.getters.userInfo
    if (!userInfo.username) {
      const userInfo = await store.dispatch('user/getUserInfo')
      // 路由的筛选
      const newRoutes = await store.dispatch(
        'permission/setRoutes',
        userInfo.roles.menus
      )
      //将动态路由添加
      router.addRoutes([
        ...newRoutes,
        { path: '*', redirect: '/404', hidden: true }
      ])
      // console.log(newRoutes)
      next(to.path)
    }

    if (to.path == '/login') {
      Message.success('已登录过1111')
      NProgress.done()
      next('/')
    } else {
      next()
    }
  } else {
    // console.log(to.path);
    const bool = whiteList.includes(to.path)
    if (bool) {
      next()
    } else {
      Message.success('还未登录过,请先登录')
      next(`/login?_redirect=${to.path}`)
    }
  }
})

//后置守卫
// 导航后置守卫(当你真正进入到某个页面之后才执行)
router.afterEach((to, from) => {
  NProgress.done()
})
